<template>
	<view class="wallet">
		<uni-tabchange :activeTab="activeTab" :tabArr="tabArr" :isFixed="true"
			@tabChangeSuccess="tabChangeSuccess"></uni-tabchange>
		<!-- 收入、消费 -->
		<view class="" v-if="activeTab!=3">
			<view class="flex alignCenter searchBox">
				<input class="search font14" v-model="searchTitle" type="text" placeholder="输入账单相关信息" placeholder-class="font14"
					@confirm="confirm">
				<view class="font16 searchBtn" @click="showPicker=true">{{searchVal.title}}</view>
			</view>
			<view class="monthBox">
				<view class="monthItem" v-for="(item,index) in list" :key="index">
					<view class="month flex alignCenter justConBetween">
						<view class="bold font18">{{item.monthTxt}}</view>
						<view class="font14 color999">{{activeTab==0?'收入':'支出'}} ￥{{item.payAmountTotal}}</view>
					</view>
					<view class="moneyList">
						<view class="flex alignCenter justConBetween listItem" v-for="(item2,idx) in item.data" :key="idx">
							<view class="flex alignCenter">
								<view class="logo">
									<!-- 数据  择校  调剂  普课  高课 -->

									<view :class="[tagsBg(item2.goodType)]" class="tagsPrimary u-font-22 tags">{{item2.goodType}}</view>
								</view>
								<view class="">
									<view class="font14 hiddenOneline">{{activeTab<2?item2.goodName:item2.foundTitle}}</view>
									<view class="font12 color999" v-if="item2.goodsType==2">{{item2.updateTime}} 查看答案</view>
									<view class="font12 color999" v-if="item2.goodsType==3">{{item2.updateTime}} 提问赏金</view>
									<view class="font12 color999" v-if="item2.goodsType==4">{{item2.updateTime}} 加入活动</view>
									<view class="font12 color999" v-if="item2.goodsType==6">{{item2.updateTime}} 找人相关</view>
									<text class="font10 colorccc">{{item2.createTime}}</text>
								</view>
							</view>
							<view class="bold">￥{{activeTab<2?item2.payAmount:item2.backAmount}}</view>
							<!-- 退款的状态 -->
							<view
								:class="item2.backState==1?'font10 bgGreen backStatus':(item2.backState==3?'font10 bgGray backStatus':'font10 bgRed backStatus')"
								v-if="activeTab==2">{{item2.backState==1?'已退款':(item2.backState==3?'退款中':'退款失败')}}</view>
						</view>
					</view>
				</view>
				<uni-nodata v-if="list.length==0" :iconStyle="{'margin':'100rpx 0 0'}"></uni-nodata>
			</view>
		</view>
		<!-- 提现 -->
		<view class="cash" v-if="activeTab==3">
			<view class="font14 cashInput">
				<input type="digit" v-model="cashMoney" placeholder="提现金额:" placeholder-class="font14">
				<view class="unit color999">元</view>
			</view>
			<view class="flex alignCenter justConAround operTip">
				<view class="font14">当前账户余额：<span class="colorF6A bold">{{allMoney}}</span>元</view>
				<view class="font14 colorF6A bold" @click="allCash">全部提现</view>
			</view>
			<view class="noWidthBtn font14" @click="cashOper">提现</view>
			<view class="noWidthBtn font14 record" @click="openCashList">查看提现记录</view>
		</view>
		<!-- 筛选 -->
		<u-select confirm-color="#F7DD5E" v-model="showPicker" value-name="val" label-name="title" mode="single-column"
			:list="typeArr" @confirm="sure"></u-select>
		<!-- 提交成功 -->
		<view class="layer" v-if="showLayer">
			<view class="font14 layerMain">
				<view class="font18 bold layerTitle">提交成功！</view>
				<view class="">我们将在<text class="bold font16">3</text>个工作日内，处理您的申请。如有疑问，请添加客服微信</view>
				<view class="">
					<image :src="serviceObj.wxCode" mode="widthFix">
					</image>
				</view>
				<view class="noWidthBtn" @click="copyWxNumebr">复制微信号</view>
				<uni-icons class="close" color="#fff" type="clear" size="40" @click="showLayer=false"></uni-icons>
			</view>
		</view>
		<!-- 选择年份 -->
		<uni-yearpicker :showYear="showYear" @cancel="cancel" @sureYear="sureYear"></uni-yearpicker>
	</view>
</template>

<script>
	import {
		walletRecord,
		walletBack,
		balanceAndProfit,
		insertWithdrawalRecords,
		getOpenid
	} from "@/api/mine.js"
	import {
		kefu
	} from "@/api/toolbox.js"
	import uniYearpicker from "@/pages/mine/components/uni-yearpicker/uni-yearpicker.vue"
	export default {
		components: {
			uniYearpicker
		},
		data() {
			return {
				serviceObj: {
					wxCode: null,
					wxNumbe: null
				},
				activeTab: 0,
				value: [0],
				indicatorStyle: `height: 40px;line-height:40px`,
				showPicker: false,
				searchTitle: '',
				searchVal: {
					title: '筛选',
					val: ''
				},
				changePickerVal: '',
				typeArr: [{
					title: '全部',
					val: ''
				}, {
					title: '问答',
					val: 1
				}, {
					title: '活动',
					val: 2
				}, {
					title: 'Vip',
					val: 3
				}, {
					title: '找人',
					val: 4
				}],
				tabArr: [{
					title: '收入'
				}, {
					title: '消费'
				}, {
					title: '退款'
				}, {
					title: '提现'
				}],
				list: [],
				year: '',
				page: 1,
				pageSize: 20,
				pageTotal: 0,
				cashMoney: '',
				allMoney: 0,
				showLayer: false,
				showYear: false,
				operChange: false,
			};
		},
		onLoad(e) {
			this.year = new Date().getFullYear()
			this.getList();
			this.getService();
			if (e.type) {
				this.tabChangeSuccess({
					activeTab: Number(e.type)
				})
			}
		},
		methods: {
			//动态获取css
			tagsBg(type) {
				let className = "";
				switch (type) {
					case '数据':
						className = 'tagsPrimary';
						break;
					case '择校':
						className = 'tagsWraning';
						break;
					case '调剂':
						className = 'tagsSuccess';
						break;
					case '普课':
						className = 'tagsDanger';
						break;
					case '高课':
						className = 'tagsInfo';
						break;
					default:
						className = 'tagsInfo';
						break;
				}
				return className;
			},
			//复制微信号
			copyWxNumebr() {
				uni.setClipboardData({
					data: this.serviceObj.wxNumbe,
					success: () => {
						uni.showToast({
							title: '已复制到剪切板！',
							icon: 'none'
						});
					},
					complete: (res) => {
						console.log('res: ', res);
					}
				})
			},
			//获取提现客服二维码和微信号
			getService() {
				kefu(2).then((res) => {
					this.serviceObj = res.data;
				})
			},
			//打开提现记录页面
			openCashList() {
				uni.navigateTo({
					url: '/pages/mine/wallet/list/index',
				});
			},
			initPage() {
				this.page = 1
				this.list = []
			},
			getList() {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				let nowMonth = (Number(new Date().getMonth()) + 1 >= 10 ? Number(new Date().getMonth()) + 1 : '0' + (Number(
					new Date().getMonth()) + 1))
				let param = {
					page: this.page,
					size: this.pageSize,
					payType: this.activeTab,
					end: (this.year == new Date().getFullYear() ? this.year + '-' + nowMonth : this.year + '-12'),
					begin: this.year + '-01',
					goodsCategory: this.searchVal.val,
				}
				if (this.activeTab < 2) {
					param.payItem = this.searchTitle
					// 收入、消费
					walletRecord(param).then((res) => {

						console.log('res.data.rows: ', res.data.rows);

						uni.hideLoading()
						if (res.code == 100000) {
							if (this.list.length > 0) {
								if (res.data.rows.length > 0) {
									res.data.rows.forEach((item) => {
										item.monthTxt = (item.yearMonth.split('-')[1] >= 10 ? item.yearMonth.split('-')[1] : item
											.yearMonth.split('-')[1].replace('0', '')) + '月'
										if (item.yearMonth == this.list[this.list.length - 1].yearMonth) {
											this.list[this.list.length - 1].data = this.list[this.list.length - 1].data.concat(item
												.data)
										} else {
											this.list.push(item)
										}
									})
								}
							} else {
								if (res.data.rows.length > 0) {
									res.data.rows.forEach((item) => {
										item.monthTxt = (item.yearMonth.split('-')[1] >= 10 ? item.yearMonth.split('-')[1] : item
											.yearMonth.split('-')[1].replace('0', '')) + '月'
									})
									this.list = res.data.rows
								}
							}

							let nowYear = new Date().getFullYear();
							let nowMonth = new Date().getMonth() + 1;
							this.list.forEach(e => {
								if (e.yearMonth === (nowYear + '-' + nowMonth)) {
									e.monthTxt = '本月';
								}
							})
							console.log('this.list: ', this.list);

							this.pageTotal = Math.ceil(res.data.total / this.pageSize)
						}
					}).catch((err) => {
						uni.hideLoading()
					})
				} else {
					param.backItem = this.searchTitle
					// 退款
					walletBack(param).then((res) => {

						uni.hideLoading()
						if (res.code == 100000) {
							if (this.list.length > 0) {
								if (res.data.rows.length > 0) {
									res.data.rows.forEach((item) => {
										item.monthTxt = (item.yearMonth.split('-')[1] >= 10 ? item.yearMonth.split('-')[1] : item
											.yearMonth.split('-')[1].replace('0', '')) + '月'
										if (item.yearMonth == this.list[this.list.length - 1].yearMonth) {
											this.list[this.list.length - 1].data = this.list[this.list.length - 1].data.concat(item
												.data)
										} else {
											this.list.push(item)
										}
									})
								}
							} else {
								if (res.data.rows.length > 0) {
									res.data.rows.forEach((item) => {
										item.monthTxt = (item.yearMonth.split('-')[1] >= 10 ? item.yearMonth.split('-')[1] : item
											.yearMonth.split('-')[1].replace('0', '')) + '月'
									})
									this.list = res.data.rows
								}
							}
							this.pageTotal = Math.ceil(res.data.total / this.pageSize)
						}
					}).catch((err) => {
						uni.hideLoading()
					})
				}
			},
			// 输入框的确定事件
			confirm() {
				this.initPage()
				this.getList()
			},
			//获取提现账户余额
			handleBalanceAndProfit() {
				uni.showLoading({
					mask: true
				});
				balanceAndProfit().then(res => {
					console.log('res: ', res.data);
					this.allMoney = res.data || 0;
				}).finally(() => {
					uni.hideLoading();
				})
			},
			tabChangeSuccess(val) {
				this.activeTab = val.activeTab
				if (val.activeTab == 3) {
					// 提现
					this.handleBalanceAndProfit();
				} else {
					// 收入、消费、退款
					this.initPage()
					this.getList()
				}
			},
			cancelClick() {
				this.operChange = false
				this.showPicker = false
			},
			sure(val) {
				this.searchVal = {
					title: val[0].label,
					val: val[0].value
				}
				this.showPicker = false;
				this.initPage()
				this.getList()
			},
			bindChange(e) {
				this.operChange = true
				this.changePickerVal = this.typeArr[e.detail.value[0]]
			},
			// 全部提现
			allCash() {
				this.cashMoney = this.allMoney
			},
			// 提现
			cashOper() {
				
				
				
				if (!this.cashMoney || Number(this.cashMoney) <= 0) {
					uni.showToast({
						title: '提现金额必须大于0',
						icon: 'none'
					})
					return
				}
				if (this.cashMoney > this.allMoney) {
					uni.showToast({
						title: '提现金额不能大于账户余额',
						icon: 'none'
					})
					return
				}
				insertWithdrawalRecords({
					money: this.cashMoney
				}).then(res => {
					if (res.code === 100000) {
						this.handleBalanceAndProfit();
						this.cashMoney = '';
						this.showLayer = true;
					} else {
						if (res.msg === '未绑定微信！')
							uni.showModal({
								title: '提示',
								content: '绑定微信，立即提现',
								cancelText: '不绑定',
								confirmText: '绑定',
								success: res => {
									if (res.confirm) {
										uni.login({
											provider: 'weixin',
											success: (wx) => {
												console.log('wx: ', wx);
												uni.showLoading({
													title: '微信绑定中...',
													mask: true
												});
												getOpenid({
													userId: uni.getStorageSync('userId'),
													authCode: wx.code
												}).then(openid=>{
													if(openid.code === 100000){
														this.cashOper();
													}
												}).finally(()=>{
													uni.hideLoading();
												})
											}
										})
									}
								},
							});
					}
				});
			},
			cancel() {
				this.showYear = false
			},
			sureYear(year) {
				this.year = year
				this.showYear = false
				this.initPage()
				this.getList()
			},
		},
		onPullDownRefresh() {
			this.initPage()
			this.getList()
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1000)
		},
		onReachBottom() {
			console.log('加载更多')
			if (this.page < this.pageTotal) {
				++this.page
				this.getList()
			} else {
				uni.showToast({
					title: '我也是有底线的',
					icon: 'none'
				})
			}
		}
	}
</script>
<style lang="scss">
	page {
		background: $pageBgColor;
	}
</style>
<style lang="scss" scoped>
	.colorF6A {
		color: #F6A030;
	}

	.wallet {
		padding: 0 30rpx 0;

		.searchBox {
			padding: 40rpx 0 0;
		}

		.calender {
			text-align: center;
		}

		.search {
			height: 80rpx;
			line-height: 80rpx;
			border: 1px solid $bordercolor;
			border-radius: 140rpx;
			flex: 1;
			padding: 0 0 0 30rpx;
			box-sizing: border-box;
			background-color: #fff;
		}

		.searchBtn {
			margin-left: 30rpx;
		}

		.monthBox {
			.monthItem {
				margin: 40rpx 0 0;
				position: relative;
			}

			.month {
				margin: 0 0 40rpx;
			}

			.moneyList {
				background: #fff;
				border-radius: 20rpx;
				padding: 0 40rpx;
				box-sizing: border-box;

				.listItem {
					position: relative;
					padding: 30rpx 0;
					border-bottom: 1px solid $bordercolor;
				}

				.listItem:last-child {
					border-bottom: none;
				}

				.logo {
					flex-shrink: 0;
					margin-right: 40rpx;

					image {
						width: 70rpx;
						height: 70rpx;
						display: block;
						border-radius: 50%;
					}
				}

				.backStatus {
					position: absolute;
					right: -40rpx;
					top: 0;
					border-radius: 0 20rpx 0 20rpx;
					padding: 5rpx 20rpx;
					box-sizing: border-box;
				}

				.bgGreen {
					background: $colorgreen;
					color: #fff;
				}

				.bgGray {
					background: #f2f2f2;
				}

				.bgRed {
					background: $colorred;
					color: #fff;
				}
			}
		}
	}

	.cash {
		background: #fff;
		margin: 40rpx 0 0;
		padding: 120rpx 70rpx 50rpx;
		box-sizing: border-box;
		height: calc(100% - 40rpx);

		.cashInput {
			height: 90rpx;
			line-height: 90rpx;
			border: 1px solid $bordercolor;
			border-radius: 180rpx;
			padding: 0 0 0 30rpx;
			box-sizing: border-box;
			position: relative;

			input {
				height: 100%;
				line-height: 90rpx;
			}

			.unit {
				position: absolute;
				right: 30rpx;
				top: 0;
			}
		}

		.operTip {
			margin: 30rpx 0 80rpx;
		}

		.noWidthBtn {
			padding: 24rpx 0;
			margin-bottom: 40rpx;
			border: 1px solid $colorMain;
		}

		.record {
			background-color: $colorMainOper;
		}
	}

	.walletPicker {
		position: fixed;
		background: rgba(0, 0, 0, .1);
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;

		.pickerMain {
			background: #fff;
			border-radius: 40rpx 40rpx 0 0;
			position: absolute;
			bottom: 0;
			left: 0;
			width: 100%;

			.title {
				padding: 30rpx;
				box-sizing: border-box;
				border-bottom: 1px solid $bordercolor;
			}
		}
	}

	.picker-view {
		width: 100%;
		height: 400rpx;
		margin-top: 20rpx;
	}

	.item {
		line-height: 40px;
		text-align: center;
	}

	.layer {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, .6);
		z-index: 100;

		.layerMain {
			background: #fff;
			width: 70%;
			margin: 30% auto 0;
			text-align: center;
			position: relative;
			// position:absolute;
			// left:0;
			// top:0;
			// bottom:0;
			// right:0;
			// margin:auto;
			padding: 60rpx 30rpx;
			box-sizing: border-box;

			.layerTitle {
				margin: 0 0 30rpx;
			}

			image {
				width: 250rpx;
				display: block;
				margin: 30rpx auto;
			}

			.noWidthBtn {
				display: inline-block;
				margin: 10rpx 0 0;
			}

			.close {
				// position:absolute;
				// left:0;
				// right:0;
				// top: 0;
				// bottom:-70rpx;
				position: relative;
				top: 140rpx;
				display: block;
			}
		}
	}

	.tags {
		padding: 4rpx 6rpx;
		border-radius: 8rpx;
		color: #fff;
	}
</style>